//Not-tabbar\HC_info\HC_info.js
import { collectCase, unCollectCase } from '../../Service/ColloctionService';
import { fetchDetailById,checkIfCollected } from '../../Service/CategoryService';

function debounce(func, wait) {
  //用于存储由 setTimeout 函数返回的 ID
  let timeout;
  return function() {
    const context = this, args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(function() {
      func.apply(context, args);
    }, wait);
  };
}

Page({
  data: {
    loading: false,
    caseDetail: {},
    otherDetails: [
      { key: 'indication', title: '适应症', image: "/static/HC_Info/折叠.png", expanded: false },
      { key: 'Medifood_usage', title: '用法', image: "/static/HC_Info/折叠.png", expanded: false },
      { key: 'treated_disease', title: '治疗疾病', image: "/static/HC_Info/折叠.png", expanded: false },
      { key: 'Medifood_aroma', title: '药膳香味', image: "/static/HC_Info/折叠.png", expanded: false },
      { key: 'Medifood_color', title: '药膳颜色', image: "/static/HC_Info/折叠.png", expanded: false },
      { key: 'Medifood_flavor', title: '药膳味道', image: "/static/HC_Info/折叠.png", expanded: false },
      { key: 'Associated_symptoms', title: '关联症状', image: "/static/HC_Info/折叠.png", expanded: false },
      { key: 'Edible_method', title: '食用方法', image: "/static/HC_Info/折叠.png", expanded: false },
      { key: 'treatment_site', title: '治疗部位', image: "/static/HC_Info/折叠.png", expanded: false },
    ],
    expandAll: false,
    expandImage: "/static/HC_Info/全部折叠.png",
    collectImage: "/static/HC_Info/收藏1.png",
  },

  // 接收传入的ID
  onLoad(options) {
    const id = options.id;
    if (id) {
      this.loadDetail(id);
    }
  },

  // 加载详情页
  async loadDetail(id) {
    try {
      const detail = await fetchDetailById(id);
      const userId = wx.getStorageSync('userId');
      const isCollected = await checkIfCollected(userId, id);
      this.setData({
        caseDetail: detail,
        loading: false,
        'caseDetail.isCollect': isCollected,
        collectImage: isCollected ? "/static/HC_Info/收藏2.png" : "/static/HC_Info/收藏1.png"
      });
    } catch (error) {
      console.error('加载详情时出错:', error);
    }
  },

  handleExpand() {
    const { caseDetail, otherDetails } = this.data;
    const newExpandStatus = !caseDetail.expandAll;

    // 更新每个详情项的展开状态和图标
    const newOtherDetails = otherDetails.map(item => ({
      //保留了原对象的所有属性
      ...item,
      expanded: newExpandStatus,
      image: newExpandStatus ? "/static/HC_Info/展开.png" : "/static/HC_Info/折叠.png",
    }));

    // 更新数据状态
    this.setData({
      'caseDetail.expandAll': newExpandStatus,
      otherDetails: newOtherDetails,
      expandImage: newExpandStatus ? "/static/HC_Info/全部展开.png" : "/static/HC_Info/全部折叠.png",
    });
  },

  handleDetailExpand(e) {
    //key--从事件对象的 dataset 中提取，用于识别哪个详情项被点击。
    const { key } = e.currentTarget.dataset || e.target.dataset;
    // 更新对应详情项的展开状态和图标
    const newOtherDetails = this.data.otherDetails.map(item => {
      if (item.key === key) {
        return {
          ...item,
          expanded: !item.expanded,
          image: !item.expanded ? "/static/HC_Info/展开.png" : "/static/HC_Info/折叠.png",
        };
      }
      return item;
    });
    // 更新数据状态
    this.setData({
      otherDetails: newOtherDetails,
    });
  },


  handleCollect: debounce(async function() {
    try {
      const userId = wx.getStorageSync('userId');
      if (!userId) {
        wx.showModal({
          title: '未登录',
          content: '请先登录再进行收藏操作',
          showCancel: false,
        });
        return;
      }
      
      // 确保 case_id 是字符串
      const caseIdStr = String(this.data.caseDetail.id);
  
      await collectCase(caseIdStr);
      this.setData({
        'caseDetail.isCollect': true,
        collectImage: "/static/HC_Info/收藏2.png",
      });
      wx.showToast({
        title: '收藏成功',
        icon: 'success'
      });
    } catch (error) {
      console.error('收藏失败:', error);
      wx.showToast({
        title: '收藏失败',
        icon: 'none'
      });
    }
  },300),
  
  handleUncollect: debounce(async function() {
    try {
      const userId = wx.getStorageSync('userId');
      if (!userId) {
        wx.showModal({
          title: '未登录',
          content: '请先登录再进行取消收藏操作',
          showCancel: false,
        });
        return;
      }
      await unCollectCase(this.data.caseDetail.id);
      
      this.setData({
        'caseDetail.isCollect': false,
        collectImage: "/static/HC_Info/收藏1.png",
      });
      wx.showToast({
        title: '取消收藏成功',
        icon: 'success'
      });
    } catch (error) {
      console.error('取消收藏失败:', error);
      wx.showToast({
        title: '取消收藏失败',
        icon: 'none'
      });
    }
  },300),
  viewImage() {
    let thumbsOf = this.data.caseDetail.thumbs;
    thumbsOf = [thumbsOf];
    wx.previewImage({
      urls: thumbsOf  // 使用正确的变量
    });
  },
});
